package com.xuanzheng.company.servlet;

import com.google.gson.Gson;
import com.xuanzheng.company.entity.Company;
import com.xuanzheng.company.service.CompanyService;
import com.xuanzheng.company.service.impl.CompanyServiceImpl;
import com.xuanzheng.company.dao.UserDao;
import com.xuanzheng.company.dao.impl.UserDaoImpl;
import com.xuanzheng.company.entity.User;
import com.xuanzheng.company.util.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@WebServlet("/admin/searchCompany")
public class SearchCompanyServlet extends HttpServlet {
    private final CompanyService companyService = new CompanyServiceImpl();
    private final UserDao userDao = new UserDaoImpl();
    private final Gson gson = new Gson();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 获取查询参数
            String keyword = request.getParameter("keyword");
            String searchType = request.getParameter("searchType"); // 可以是id, manager, creditCode
            
            List<Company> companies = new ArrayList<>();
            
            if (keyword == null || keyword.trim().isEmpty()) {
                // 如果没有关键词，返回所有公司
                companies = companyService.getAllCompanies();
            } else {
                // 根据不同的搜索类型进行搜索
                switch (searchType) {
                    case "id":
                        Company company = companyService.getCompanyById(keyword.trim());
                        if (company != null) {
                            companies.add(company);
                        }
                        break;
                    case "manager":
                        // 先查找匹配名字的用户
                        List<User> managers = findUsersByName(keyword.trim());
                        // 然后查找这些用户管理的公司
                        for (User manager : managers) {
                            Company managerCompany = companyService.getCompanyByManagerId(manager.getId());
                            if (managerCompany != null) {
                                companies.add(managerCompany);
                            }
                        }
                        break;
                    case "creditCode":
                        Company creditCodeCompany = companyService.getCompanyByCreditCode(keyword.trim());
                        if (creditCodeCompany != null) {
                            companies.add(creditCodeCompany);
                        }
                        break;
                    default:
                        // 默认返回所有公司
                        companies = companyService.getAllCompanies();
                        break;
                }
            }
            
            // 添加公司负责人信息
            List<Map<String, Object>> companyList = new ArrayList<>();
            for (Company company : companies) {
                Map<String, Object> companyMap = new HashMap<>();
                companyMap.put("id", company.getId());
                companyMap.put("name", company.getName());
                companyMap.put("address", company.getAddress());
                companyMap.put("phone", company.getPhone());
                companyMap.put("creditCode", company.getCreditCode());
                companyMap.put("employeeCount", company.getEmployeeCount());
                companyMap.put("status", company.getStatus());
                companyMap.put("createTime", company.getCreateTime());
                
                // 获取负责人信息
                User manager = userDao.findById(company.getManagerId());
                if (manager != null) {
                    Map<String, Object> managerInfo = new HashMap<>();
                    managerInfo.put("id", manager.getId());
                    managerInfo.put("name", manager.getName());
                    managerInfo.put("phone", manager.getPhone());
                    companyMap.put("manager", managerInfo);
                }
                
                companyList.add(companyMap);
            }
            
            result.put("success", true);
            result.put("companies", companyList);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "搜索公司失败：" + e.getMessage());
        }
        
        out.write(gson.toJson(result));
        out.flush();
    }
    
    // 辅助方法：根据姓名查找用户
    private List<User> findUsersByName(String name) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List<User> users = new ArrayList<>();
        
        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT * FROM user WHERE name LIKE ? AND role = 1"; // 只查找公司负责人
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, "%" + name + "%");
            rs = pstmt.executeQuery();
            
            while (rs.next()) {
                User user = new User();
                user.setId(rs.getString("id"));
                user.setName(rs.getString("name"));
                user.setPhone(rs.getString("phone"));
                user.setRole(rs.getInt("role"));
                users.add(user);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, rs);
        }
        
        return users;
    }
} 